package com._51cto.healthy.service;

import com._51cto.healthy.base.BaseMapper;
import com._51cto.healthy.content.P;
import com._51cto.healthy.mapper.MenuMapper;
import com._51cto.healthy.mapper.PermissionMapper;
import com._51cto.healthy.mapper.RoleMapper;
import com._51cto.healthy.pojo.Role;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public BaseMapper<Role> getDao() {
        return roleMapper;
    }

    @Override
    public P<Role> queryRoleIds(String query, Integer pageNum, Integer pageSize) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roles = roleMapper.queryRoleAll(query);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return new P().setPageNum(pageInfo.getPageNum())
                .setPageSize(pageInfo.getPageSize())
                .setPages(pageInfo.getPages())
                .setRows(pageInfo.getList())
                .setTotal(pageInfo.getTotal());
    }

    @Override
    @Transactional
    public void insertRoleMenuPermission(Role role) {
        //添加角色
        roleMapper.insert(role);
        System.out.println(role.getPermissionIds());
        System.out.println(role.getMenuIds());

    }

    @Override
    @Transactional
    public void updateRoleMenu(Role role) {
        //先修改role
        roleMapper.update(role);
        //通过Role的ID删除对应的关联表menu
        roleMapper.deleteByPK(role.getId());
        //通过Role的ID删除对应的关联表permision
        roleMapper.deleteByPK2(role.getId());
        //遍历循环添加角色对应的permission表字段
        role.getPermissionIds().forEach( pId ->{
            roleMapper.insertPermissionIds(role.getId(),pId);

        });
        //遍历循环添加角色对应的menu表的字段
        role.getMenuIds().forEach(menuId ->{
            roleMapper.insertMenuIds(role.getId(),menuId);
        });
    }

    @Override
    @Transactional
    public void deleteRoleMenu(Integer id) {
        //通过Role的ID删除对应的关联表menu
        roleMapper.deleteByPK(id);
        //通过Role的ID删除对应的关联表permision
        roleMapper.deleteByPK2(id);
        roleMapper.deleteByPK3(id);
    }
}
